package com.gaoda.booksystem.web.user;

import com.gaoda.booksystem.entity.Book;
import com.gaoda.booksystem.entity.Borrowing;
import com.gaoda.booksystem.entity.Revert;
import com.gaoda.booksystem.service.UserService;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author: LuckyBear
 * @date: 2018-12-13 21:18
 * @description:
 */
@Controller
public class BookController {
    //分页
    private static final long serialVersionUID = 1L;
    private static final int PAGE_COUNT = 3;//每页显示记录数

    @Autowired
    UserService userService;

    //模糊查询显示用户列表 + 分页
    @RequestMapping("/index")
    public String queryBookList(Principal principal, String bookName, String bookPublishers, String bookType, Model model, HttpServletRequest request) {
        String username = principal.getName();
        model.addAttribute("username", username);
        //默认当前页
        int currentPage = 1;
        String page = request.getParameter("page");
        if (page != null) {
            currentPage = Integer.valueOf(page);
        }
        List<Book> list = userService.findBooks(bookName, bookPublishers, bookType, currentPage, PAGE_COUNT);
        int totalPage = userService.getTotal(PAGE_COUNT, bookName, bookPublishers, bookType);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("booklist", list);
        model.addAttribute("bookName", bookName);
        model.addAttribute("bookPublishers", bookPublishers);
        model.addAttribute("bookType", bookType);
        return "user/index";
    }

    //我的书籍
    @RequestMapping("/myBook")
    public String myBook(Principal principal, Model model) {
        String username = principal.getName();
        model.addAttribute("username", username);

        List<Borrowing> list = userService.myBooks(username);
        model.addAttribute("booklist", list);
        return "user/userBook";
    }

    //书籍详情
    @RequestMapping("/bookDetails")
    public String bookDetails(Model model, String bookNumber, Principal principal) {
        String username = principal.getName();
        model.addAttribute("username", username);
        Book book = userService.findBookByNumber(bookNumber);
        List<Borrowing> list = userService.queryBorrowing(bookNumber);
        model.addAttribute("book", book);
        model.addAttribute("list", list);
        return "user/bookDetails";
    }

    //借书
    @RequestMapping("/borrowingBook")
    @ResponseBody
    public String borrowingBook(Principal principal, String bookNumber) {
        String username = principal.getName();  //获取用户账号
        int num = userService.findBookByNumber(bookNumber).getBookNum();
        if (num == 0) {
            //本书余量不足，借阅失败
            return "3";
        }
        Date date = new Date();
        Borrowing borrowing = new Borrowing(date, username, bookNumber);
        List<Borrowing> borrowingList = userService.findBorrowing(borrowing);
        List<Borrowing> borrowingList1 = userService.findBorrowingBook(borrowing);
        if (borrowingList.size() > 0) {
            //借阅过本书，借阅失败
            return "2";
        }
        if (borrowingList1.size() > 1) {
            //借阅的书超过2本，借阅失败
            return "4";
        }
        userService.borrowingBook(borrowing);
        userService.updateBookNumLess(bookNumber);
        return "1";
    }

    //还书
    @RequestMapping("/revert")
    public String revert(Principal principal, String bookNumber) {
        String username = principal.getName();  //获取用户账号
        Date date = new Date();
        Revert revert = new Revert(date, username, bookNumber);
        Borrowing borrowing = new Borrowing(date, username, bookNumber);
        userService.revertBook(revert);
        userService.updateBookFlag(borrowing);
        userService.updateBookNumMore(bookNumber);
        return "redirect:myBook";
    }

    //改变页面借阅书籍按钮样式
    @RequestMapping("/borrowingFettle")
    @ResponseBody
    public String borrowingFettle(Principal principal, String bookNumber) {
        String username = principal.getName();  //获取用户账号
        Date date = new Date();
        Borrowing borrowing = new Borrowing(date, username, bookNumber);
        List<Borrowing> borrowingList = userService.findBorrowing(borrowing);
        if (borrowingList.size() > 0) {
            return "1";
        }
        return "2";
    }

    //导出图书信息
    @RequestMapping(value = "/loadBook", method = RequestMethod.GET)
    public void loadBook(HttpServletResponse response) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("书籍信息表");
        //获取数据
        List<Book> bookList = userService.AllBook();

        //设置要导出的文件的名字
        String fileName = "BookList" + ".xls";

        //新增数据行，并且设置单元格数据
        int rowNum = 1;

        //headers表示excel表中第一行的表头
        String[] headers = {"书号", "书名", "作者", "出版社", "入库时间", "简介", "总数", "余量"};

        //在excel表中添加表头
        HSSFRow row = sheet.createRow(0);

        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Book book : bookList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(book.getBookNumber());
            row1.createCell(1).setCellValue(book.getBookName());
            row1.createCell(2).setCellValue(book.getBookAuthor());
            row1.createCell(3).setCellValue(book.getBookPublishers());
            row1.createCell(4).setCellValue(sdf.format(book.getBookTime()));
            row1.createCell(5).setCellValue(book.getBrief());
            row1.createCell(6).setCellValue(book.getBookAllNum());
            row1.createCell(7).setCellValue(book.getBookNum());
            rowNum++;
        }

        //根据内容自动调整列宽
        HSSFSheet hssfSheet = workbook.getSheetAt(0);
        hssfSheet.autoSizeColumn((short)0);
        hssfSheet.autoSizeColumn((short)1);
        hssfSheet.autoSizeColumn((short)2);
        hssfSheet.autoSizeColumn((short)3);
        hssfSheet.autoSizeColumn((short)4);
        hssfSheet.autoSizeColumn((short)6);
        hssfSheet.autoSizeColumn((short)7);

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename="+ fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
}
